import config from '@/config'

const header = {
    'Content-Type': 'application/json'
    // 'Content-Type': 'application/x-www-form-urlencoded'
}

// 任务队列
export const taskMap = new Map()

// 普通请求
const http = (options) => {
    if (!options.url.includes('https://')) {
        options.url = config.baseUrl + options.url
    }
    return new Promise((resolve) => {
        const requestTask = uni.request({
            header,
            ...options,
            success: (res) => {
                resolve(res)
            },
            fail: (err) => {
                resolve(err)
            }
        })
        const { url } = options
        if (options.only) {
            if (taskMap.has(url)) {
                taskMap.get(url).abort()
            }
        }
        taskMap.set(url, requestTask)
    })
}

export default http

// 文件上传请求
export const http_file = (path) => {
    return uni.uploadFile({
        url: '/file/upload',
        filePath: path,
        name: 'file',
        header: {
            'Content-Type': 'multipart/form-data'
        }
    }).catch((err) => err)
}


// 中断所有请求
export const abortTaskAll = () => {
    taskMap.forEach((val) => {
        val && val.abort()
    })
    taskMap.clear()
}
